package menu

import (
	"context"
	"net/http"

	"go-zero-admin/apps/system/cmd/api/internal/svc"
	"go-zero-admin/apps/system/cmd/api/internal/types"
	"go-zero-admin/apps/system/cmd/rpc/syspb"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetMenuLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *http.Request
}

func NewGetMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext, r *http.Request) *GetMenuLogic {
	return &GetMenuLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		r:      r,
	}
}

func (l *GetMenuLogic) GetMenu(req *types.GetMenuReq) (resp *types.GetMenuResp, err error) {
	// 获取菜单数据
	menuResp, err := l.svcCtx.MenuRpc.GetMenuOne(l.ctx, &syspb.GetMenuOneReq{
		Id: req.Id,
	})
	if err != nil {
		return nil, err
	}

	var menu types.SysMenu
	_ = copier.Copy(&menu, menuResp.GetOne())

	// 获取该菜单角色数据
	menuRoleIdsResp, err := l.svcCtx.MenuRpc.GetMenuRoleIds(l.ctx, &syspb.GetMenuRoleIdsReq{
		Id: req.Id,
	})
	if err != nil {
		return nil, err
	}
	roleIds := menuRoleIdsResp.GetRoleIds()
	if len(roleIds) == 0 {
		roleIds = []int64{}
	}

	return &types.GetMenuResp{
		Rule:    &menu,
		RoleIds: roleIds,
	}, nil
}
